import setUserTempId from "@/utils/userTempId"

import {
    requestLogin,
    requestUserInfo,
    requestLogout,
} from "@/api"

//home模块的配置
const state = {
    userTempId: setUserTempId(),
    token: localStorage.getItem("user_token") || "",
    nickName: "",
}

const mutations  = {
    SET_TOKEN_STATE(state , value){
        state.token = value
    },

    //获取用户名
    SET_USERINFO_STATE(state , value){
        state.nickName = value
    },

    //退出登录
    SET_LOGOUT_STATE(state){
        state.token = "",
        state.nickName = "",
        localStorage.removeItem("user_token")
    }
}
const actions = {
    //登录请求
    async getLogin({commit}, userInfo){
        //发送请求
        const result = await requestLogin(userInfo)
        commit("SET_TOKEN_STATE" , result.token)
        //保存token
        localStorage.setItem("user_token" , result.token)
    },

    //获取用户名
    async getUserName({commit}){
        const result = await requestUserInfo()
        commit("SET_USERINFO_STATE" , result.nickName)
    },

    //退出登录
    async getLogout({commit}){
        await requestLogout()
        commit("SET_LOGOUT_STATE")
    }
    
}
const getters = {}

export default {
    //开启命名空间
    namespaced: true,
    state,
    mutations,
    actions,
    getters,
}